package com.cs.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cs.constant.MenuConstant;
import com.cs.domain.SysMenu;
import com.cs.mapper.SysMenuMapper;
import com.cs.service.SysMenuService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService{
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private SysMenuMapper sysMenuMapper;
    /**
     * 查询用户的菜单
     * 需要先查询缓存
     * @param userId
     * @return
     */
    @Override
    public List<SysMenu> findMenus(String userId) {
        //缓存中的数据
        String jsonMenus = redisTemplate.opsForValue().get(MenuConstant.MENU_PREFIX + userId);
        List<SysMenu> sysMenus=null;
        if(!StringUtils.isEmpty(jsonMenus)){
            sysMenus = JSON.parseArray(jsonMenus, SysMenu.class);
            return sysMenus;
        }
        //用户的菜单
        List<SysMenu> menus=sysMenuMapper.findMenus(Long.valueOf(userId));
        //构建属性菜单
        sysMenus=treeMenus(0L,menus);
        if(!CollectionUtils.isEmpty(sysMenus)){
            //存入redis中
            jsonMenus = JSON.toJSONString(sysMenus);
            redisTemplate.opsForValue().set(MenuConstant.MENU_PREFIX+userId,jsonMenus, Duration.ofDays(7));
        }
        return sysMenus;
    }

    /**
     * 树性菜单
     * @param pid
     * @param menus
     * @return
     */
    private List<SysMenu> treeMenus(Long pid, List<SysMenu> menus) {
        //根菜单
        List<SysMenu> root = menus.parallelStream().filter(sysMenu -> sysMenu.getParentId().equals(pid)).collect(Collectors.toList());
        root.forEach(r->{
            //子菜单
            List<SysMenu> subMenus = menus.stream().filter(sysMenu -> sysMenu.getParentId().equals(r.getMenuId())).collect(Collectors.toList());
            //设置子菜单
            r.setList(subMenus);
        });
        return root;
    }
}
